<!--
*@Author: zt
*@Description: 出差申请
*@Date: 2024-08-09
-->
<template>
  <u-dialog
    v-bind="$attrs"
    :confirmLoading="formLoading"
    @submit="submit"
    @close="dialogClose"
    :hideBtns="route.params.pType == '2' || ['2', '3'].includes(form.status + '') ? ['submit'] : []">
    <a-layout class="f-h-100">
      <a-layout-content
        class="s-bg-white"
        style="overflow: auto">
        <u-flow-tab
          activeKey="1"
          :show="isValue(form.status)"
          :isAudit="form.status == 2"
          :isAuditPage="route.params.pType == '2'"
          :params="{ type: 'travel_apply', ...form }"
          v-bind="$attrs"
          ref="auditRef">
          <a-tab-pane
            key="1"
            tab="基本信息">
            <a-space
              direction="vertical"
              class="f-w-100">
              <u-busi-card
                title="基本信息"
                :bordered="false">
                <u-form
                  :elements="formEls"
                  :loading="formLoading"
                  :model="form"
                  :gutter="0"
                  :disabled="['2', '3'].includes(form.status + '')"
                  ref="formRef"></u-form>
              </u-busi-card>
            </a-space>
          </a-tab-pane>
        </u-flow-tab>
      </a-layout-content>
      <!-- 出差人查看 -->
      <ccPeople
        v-model:open="ppdialogshow"
        :is-check="true"
        wrap-class-name="full-modal"
        :keyid="$attrs.keyid"
        :checkedKeys="checkedKeys"
        @submit="submitEvectionTab"
        @close="isFocus = false" />
    </a-layout>

    <template
      v-slot:footerBefore
      v-if="route.params.pType == '1' && !['2', '3'].includes(form.status + '')">
      <u-icon-button
        itype="save"
        @click="submit('up')">
        保存并上报
      </u-icon-button>
    </template>
    <template
      #footerBefore
      v-if="route.params.pType == '2' && ['2', '3'].includes(form.status + '')">
      <u-icon-button
        itype="approve"
        @click="auditAbout('2')">
        批准
      </u-icon-button>
      <u-icon-button
        itype="close"
        @click="auditAbout('3')">
        退回
      </u-icon-button>
    </template>
  </u-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, useAttrs, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { _IFormEl, _IExtra } from "@/src/components/common/form/interface";
import { FormInstance, FormItemProps, Cascader } from "ant-design-vue";
import { _IColumnProps } from "@/components/common/tableEdit/interface.ts";
import { messageC, alertC, isValue } from "@/util/common";
import { storeToRefs } from "pinia";
import { useLoginStore, useBaseStore } from "@/store";
import { useAuditAbout, IAuditParams } from "@/hooks/useAudit";
import { cloneDeep } from "lodash";
import dayjs from "dayjs";
import ccPeople from "./ccPeople.vue";
import * as travelApi from "@/service/administration/travel";
import * as deptApi from "@/service/system/dept";
import * as areaApi from "@/service/system/area";

let formDisabled = ref<any>(false);
const route = useRoute();
const router = useRouter();
const attrs = useAttrs();
const emits = defineEmits(["success", "close"]);
const fileData = ref([]);
const { userInfo } = storeToRefs(useLoginStore());
const { TRAVEL_TYPE, TRAVEL_APPLY_WAY } = storeToRefs(useBaseStore());
let auditRef = ref();
// 表单信息
const formLoading = ref<boolean>(false);
const formRef = ref<FormInstance>();
let form = ref<object>({});

const formItemProps: FormItemProps & _IExtra = {
  labelWidth: "130px",
  colon: false,
};

const baseSelData = reactive({
  regions: [],
  deptData: [],
  userData: [],
  fkareaidDate: [],
  traveltypeData: [],
});
const ppdialogshow = ref<boolean>(false);

const isFocus = ref<boolean>(false);
const formEls: Array<_IFormEl> = reactive([
  {
    label: "填报部门",
    key: "redeptname",
    col: { span: 8 },
    element: "select",
    formItemProps: { ...formItemProps, required: true },
    componentProps: {
      options: computed(() => baseSelData.deptData),
      fieldNames: { label: "redeptname", value: "keyid" },
      disabled: true,
    },
  },
  {
    label: "申请人",
    key: "fkusername",
    col: { span: 8 },
    element: "input",
    formItemProps: { ...formItemProps, required: true },
    componentProps: { disabled: true, placeholder: "请录入申请人" },
  },
  {
    label: "填报日期",
    key: "evectiondate",
    col: { span: 8 },
    element: "datepicker",
    formItemProps: { ...formItemProps, required: true },
  },
  {
    label: "出差人员",
    key: "evectionuser",
    col: { span: 24 },
    element: "input",
    formItemProps: { ...formItemProps, required: true },
    componentProps: {
      readonly: true,
      placeholder: "请选择出差人员",
      onClick: () => {
        if (isFocus.value == false) {
          (ppdialogshow.value = true), (isFocus.value = true);
        }
      },
    },
  },
  {
    label: "出差类型",
    key: "traveltype",
    col: { span: 8 },
    element: "select",
    formItemProps: { ...formItemProps, required: true },
    componentProps: {
      options: computed(() => TRAVEL_TYPE.value.filter((item) => item.code != 2)),
      fieldNames: { label: "name", value: "code" },
    },
  },
  {
    label: "起始地",
    key: "fkareaidstart",
    col: { span: 8 },
    element: "selAddress",
    formItemProps: { ...formItemProps, required: true },
    componentProps: {
      onChange: (vals, options) => {
        form.value.startAreaCn = (options || []).map((i) => i.name).join("/");
      },
    },
  },
  {
    label: "目的地",
    key: "fkareaidend",
    col: { span: 8 },
    element: "selAddress",
    formItemProps: { ...formItemProps, required: true },
    componentProps: {
      onChange: (vals, options) => {
        form.value.endAreaCn = (options || []).map((i) => i.name).join("/");
      },
    },
  },
  {
    label: "出行方式",
    key: "travelway",
    col: { span: 8 },
    element: "select",
    formItemProps: { ...formItemProps, required: true },
    componentProps: {
      options: TRAVEL_APPLY_WAY.value,
      fieldNames: { label: "name", value: "code" },
    },
  },
  {
    label: "开始时间",
    key: "startdate",
    col: { span: 8 },
    element: "datepicker",
    formItemProps: { ...formItemProps, required: true },
  },
  {
    label: "结束时间",
    key: "enddate",
    col: { span: 8 },
    element: "datepicker",
    formItemProps: { ...formItemProps, required: true },
  },
  // {
  //   label: "预计费用",
  //   key: "evectionamount",
  //   col: { span: 6 },
  //   element: "input",
  //   formItemProps: { ...formItemProps, required: true },
  //   componentProps: { disabled: computed(() => formDisabled.value) },
  // },
  {
    label: "出差事由",
    key: "evectionreason",
    col: { span: 24 },
    element: "textarea",
    formItemProps: { ...formItemProps, required: true },
  },
  {
    label: "附件",
    key: "appendix",
    col: { span: 24 },
    element: "file",
    formItemProps: { ...formItemProps, required: false },
    componentProps: {
      fileParams: {
        bucket: "FIN_BIZ_TYPE_EVECTION",
        biztype: "2",
      },
    },
  },
]);

// 出差人暴露出的事件
const submitEvectionTab = (evectionTab) => {
  let evectionuser = [];
  evectionTab.map((e) => {
    evectionuser.push(e.reusername);
  });
  form.value.evectionuser = evectionuser.join(",");
  form.value.users = evectionTab;

  ppdialogshow.value = false;

  formRef.value.form.validateFields(["evectionuser"]);

  setTimeout(() => (isFocus.value = false), 500);
};

// 确认提交
const submit = async (type?: string) => {
  try {
    await formRef.value.form.validate();
  } catch (error) {
    messageC("请填写完整表单");
    return;
  }
  const tForm = cloneDeep(form.value);
  const url = attrs.keyid ? "update" : "add";
  tForm.status = 1;
  formLoading.value = true;
  try {
    const res = await travelApi[url](tForm);
    if (res.code == 0) {
      if (type != "up") {
        messageC(res.msg, "success");
      }
      if (url == "add") {
        form.value.status = res.data["status"];
        form.value.keyid = res.data["keyid"];
      }
      if (type == "up") {
        await auditAbout("1");
      }

      dialogClose();
      emits("success");
    } else {
      alertC(res.msg, "warning");
    }
  } catch (error) {}

  formLoading.value = false;
};

// 初始化表单数据
const initForm = () => {
  form.value = {
    fkuserid: userInfo.value["userId"],
    fkusername: userInfo.value["name"],
    evectiondate: dayjs().format("YYYY-MM-DD"),
    fkdeptid: userInfo.value["deptId"],
    redeptname: userInfo.value["deptName"],
    ssdeptid: userInfo.value["deptId"],
    ssdeptname: userInfo.value["deptName"],
    fkunitsid: userInfo.value["unitId"],
    unitName: userInfo.value["unitName"],
    users: [],
    evectionuser: "",
    fkareaidstart: "",
    fkareaidend: "",
    startdate: "",
    isdelete: 0,
  }
}

// 弹窗关闭
const dialogClose = () => {
  form.value = {};
  fileData.value = [];

  formRef.value.form.resetFields();

  emits("close");
};

// 获取部门
const getDep = async () => {
  try {
    const data = await deptApi.validTree(userInfo.value["unitId"]);

    if (data.code == 0) {
      baseSelData.deptData = data.data;
    }
  } catch (error) {}
};

// 获取地区
const getFkareaid = async () => {
  try {
    const data = await areaApi.validTree(userInfo.value["unitId"]);
    if (data.code == 0) {
      baseSelData.fkareaidData = data.data;
    }
  } catch (error) {}
};

// 点击下拉框获取人员
const getUser = async ({ key, value }) => {
  if (key == "ssdeptid") {
    const res = await travelApi.evectionUserTree(value);
    if (res.code == 0) {
      baseSelData.userData = res.data;
    }
  }
};

// 上报、审核、退回
const auditAbout = async (type: string | number) => {
  const auditParams: IAuditParams = {
    type: "travel_apply",
    selDatas: [form.value],
    confirm: false,
    isDialog: false,
  };
  try {
    // 上报
    const res = await useAuditAbout(type, auditParams, auditRef);
    if (res) {
      messageC(res.msg, "success");
      emits("success");
    }
  } catch (error) {}
};

const checkedKeys = ref();
const routerDialogClose = ref(false);
// 回显
const getHxData = async () => {
  routerDialogClose.value = true;
  formLoading.value = true;
  try {
    const data = await travelApi.query(attrs.keyid);
    if (data.code == 0) {
      for (let key in data.data) {
        form.value[key] = cloneDeep(data.data[key]);
      }
      fileData.value = data.data["appendix"];

      let evectionuser = [];
      checkedKeys.value = [];
      form.value.users.forEach((e) => {
        evectionuser.push(e.reusername);
        checkedKeys.value.push(e.fkuserid);
      });
      form.value.evectionuser = evectionuser.join(",");
    }
  } catch (error) {}
  formLoading.value = false;
};

const getEnmu = async () => {
  getDep();
  getFkareaid();
};

watch(
  () => attrs.open,
  (nval, oval) => {
    if (nval == true) {
      initForm();
      getEnmu();

      if (attrs.keyid != "") {
        getHxData();
        form.value.keyid = attrs.keyid;
        formDisabled.value = attrs.formDisabled;
      }
      formDisabled.value = attrs.formDisabled;
    }
  }
);
</script>

<style lang="scss"></style>
